<template>
    <div class="have-footer contact-index">
        <template v-if='pageLoaded'>
            <div class="contact-head-box">
                <div class="contact-head contact__search">
                    <div class="contact-head__left">
                        <i class="icon"><img src="../images/search.png"></i>
                        <input
                            type="text" 
                            placeholder="搜索联系人" 
                            class='font-body1' 
                            v-model='searchValue'
                            @input='search'
                            @focus='show_mask = true' 
                            @blur='show_mask = false'>
                    </div>
                    <span v-show='!searchValue' class="contact-head__right">共{{list.length || 0}}位联系人</span>
                    <div class="contact-head__right" v-show='searchValue'>
                        <span class='button pure auto right' @click='search'>搜索</span>
                        <span v-show='show_search' class='button pure auto right' @click='searchClose'>取消</span>
                    </div>
                </div>
            </div>
            <div class="wrapper" ref='content'>
                <div class="contact-head contact__new" @click='goContactAdd'>
                    <div class="contact-head__left">
                        <i class="icon"><img src="../images/contacticon.png"></i>
                        <p class='font-body1 new'>新联系人</p>
                    </div>
                    <span class="contact-head__right font-caption" :class='{redhot:isRedhot}'>查看／添加新联系人</span>
                    <i class="iconfont icon-arrow"></i>
                </div>
                <div class="page-placeholder" v-if='!contacts.length'><span>暂无联系人</span></div>
                <div class="contact__content">
                    <div class="contact__box" v-for='item in contacts'>
                        <div class="contact__letter">{{item.letter}}</div>
                        <ul class="contact__list">
                            <li class="contact__item" v-for='subItem in item.info' @click='setPosition($event, subItem)'>
                                <img :src="(subItem.user && subItem.user.avatar) || placeholderImg" alt="">
                                <p>{{(subItem.user && subItem.user.realName) || (subItem.user && subItem.user.mobile)}}</p>
                                <span v-if='subItem.remarks'> {{subItem.remarks}} </span>
                                <i class="new" v-show='subItem.isNew'>NEW</i>
                            </li>
                        </ul>
                    </div>
                </div>
            </div>
            <transition name='fade'>
                <div class="contact__mask" v-show='show_mask'></div>
            </transition>
            <transition name='fade'>
                <div class="contact__search-detail" v-show='show_search && searchValue'>
                    <div class="page-placeholder" v-if='!filterList.length'><span>没有搜索到联系人</span></div>
                    <ul class="contact__list">
                        <li class="contact__item" v-for='item in filterList' @click='setPosition($event, item)'>
                            <img :src="item.user.avatar"> 
                            <p>{{item.user.realName || item.user.mobile}}</p> 
                            <i class="new" v-show='item.isNew'>NEW</i>
                        </li>
                    </ul>
                </div>
            </transition>
            <ul class="contact__letters">
                <li class="contacrt__letters-item" v-for='(item,index) in contacts' @click='scrollToLetter(index)'> {{item.letter}} </li>
            </ul>
            <transition name='fade'>
                <div class="operate-modal" v-show='show_operate'>
                    <div class="operate-modal-mask" @click='show_operate = false'></div>
                    <div class="operate" :style='{top:curPos+"px"}' :class='direction'>
                        <div class="operate__left">
                            <div class="operate__item" @click='goChat'>
                                <span><img src="../images/contact_chat.png"></span>
                                <p class='font-body2'>发消息</p>
                            </div>
                            <div class="operate__item" @click='goContactDetail'>
                                <span><img src="../images/contact_info.png"></span>
                                <p class='font-body2'>看资料</p>
                            </div>
                            <div class="operate__item" @click='showContactRemark'>
                                <span><img src="../images/contact_remark.png"></span>
                                <p class='font-body2'>写备注</p>
                            </div>
                        </div>
                        <div class="operate__right" @click='showContactDelete'>
                            <div class="operate__item">
                                <span><img src="../images/contact_delete.png"></span>
                                <p class='font-body2'>删除</p>
                            </div>
                        </div>
                    </div>
                </div>
            </transition>

            <confirm 
                :show='show_contact_delete'
                @close='show_contact_delete = false'
                @confirm='deleteContact'
                title='确认删除'
                tips='是否确认删除联系人？'></confirm>

            <confirm 
                :show='show_contact_remark'
                @close='show_contact_remark = false'
                @confirm='remarkContact'
                title='备注'
                tips='添加联系人备注'>
                <textarea class="confirm-textarea" placeholder="请填写联系人备注" rows='2' v-model='remark'></textarea>
            </confirm>
        </template>

        <footer-bar></footer-bar>

    </div>
</template>

<script>
    import { Promise } from 'es6-promise'
    import  { mapGetters, mapActions }  from 'vuex'
    import footerBar from '../components/FooterBar.vue'
    import { contactApi } from '../api/api'
    import { getOS } from '../utils/utils'
    import dynamics from 'dynamics.js'
    import { convertRequestURL } from '../utils/utils'
    import loading from '../components/Loading.vue'
    import confirm from '../components/Confirm.vue'
    import moment from 'moment'

    const windowHeight = $(window).height()

    export default {
        components:{
            loading,
            footerBar,
            confirm
        },
        data() {
            return {
                os:getOS(),
                pageLoaded:'',
                searchValue:'',
                remark:'',
                searchList:[],
                curPos:'',
                curUser:{},
                direction:'top',
                isRedhot:false,
                show_mask:false,
                show_search:false,
                show_operate:false,
                show_contact_delete:false,
                show_contact_remark:false,
                loading_contact_search:true,
                placeholderImg:require('../images/loading_1.png'),
                letterPos:[],
                list:[],
                placeholder:'--',
            }
        },
        computed:{
            ...mapGetters([
                'msgTip',
                'localInfo'
            ]),
            userInfo(){
                return this.localInfo.userInfo
            },
            needLogin(){
                return this.localInfo.needLogin
            },
            contacts(){
                if(this.list.length){
                    let groupList = _.groupBy(this.list,'headFirstChar')
                    let arrGroupList = []
                    let keys = Object.keys(groupList)
                    _.each(keys,function(i){
                        arrGroupList.push({
                            letter:i,
                            info:groupList[i]
                        })
                    })
                    arrGroupList = _.sortBy(arrGroupList,'headFirstChar')
                    return arrGroupList
                }
                return []
            },
            filterList(){
                let arr = []
                if(!this.list.length || !this.searchValue) return []
                _.each(this.list,(value,index)=>{
                    if(_.includes(value.user.mobile,this.searchValue) || _.includes(value.user.realName,this.searchValue) ){
                        arr.push(value)
                    }
                })
                return arr
            },
        },
        methods:{
            // actions
            ...mapActions([
                'showLoading',
                'hideLoading',
                'setMsgTip'
            ]),

            // function
            setPosition(event,item){
                if(this.userInfo.user){
                    if(!this.userInfo.user.bizRole){
                        this.$router.push({
                            name:'id-select'
                        })
                        return false
                    }
                }
                this.curUser = item
                let top = $(event.currentTarget).offset().top
                if(windowHeight - 230 < top){
                    this.curPos = top - 110
                    this.direction = 'bottom'
                }
                else{
                    this.curPos = top + 65
                    this.direction = 'top'
                }
                this.show_operate = true
            },
            showContactDelete(){
                this.show_contact_delete = true
                this.show_operate = false
            },
            showContactRemark(){
                this.show_contact_remark = true
                this.show_operate = false
                this.remark = this.curUser.remarks
            },
            deleteContact(){
                let index = _.findIndex(this.list,this.curUser)
                this.showLoading()
                contactApi.delete({
                    contactIds:this.curUser.contactId
                })
                .then(result=>{
                    this.setMsgTip({
                        text:'删除联系人成功！',
                        type:'success'
                    })
                    this.list.splice(index,1)
                    this.show_contact_delete = false
                    this.hideLoading()
                })
                .catch(error => {
                    console.error(error)
                    this.hideLoading()
                })
            },
            remarkContact(){
                let index = _.findIndex(this.list,this.curUser)
                this.showLoading()
                contactApi.remark({
                    contactId:this.curUser.contactId,
                    remarks:this.remark
                })
                .then(result=>{
                    this.setMsgTip({
                        text:'备注联系人成功！',
                        type:'success'
                    })
                    this.list[index].remarks = this.remark
                    this.remark = ''
                    this.show_contact_remark = false
                    this.hideLoading()
                })
                .catch(error => {
                    console.error(error)
                    this.hideLoading()
                })
            },
            search(){
                this.show_search = true
            },
            searchClose(){
                this.show_search = false
            },
            checkLogin(){
                if(this.needLogin){
                    this.$router.push({
                        name:'bind-phone'
                    })
                    return false
                }
                if(this.userInfo.user){
                    if(!this.userInfo.user.bizRole){
                        this.$router.push({
                            name:'id-select'
                        })
                        return false
                    }
                }
                return true
            },
            goContactAdd(){
                if(!this.checkLogin()) return
                this.$router.push({
                    name:'contact-add'
                })
            },
            goChat(){
                if(!this.userInfo.isPay || this.userInfo.isExpired){
                    this.setMsgTip({
                        text:'请先完成信用报告',
                        type:'info'

                    })
                    return
                }
                
                if(!this.checkLogin()) return

                this.showLoading()
                contactApi.im({
                    uuid:this.curUser.user.uuid
                })
                .then(result=>{
                    this.hideLoading()
                    let info = result.info
                    let myAccid = info.myAccid
                    let accid = info.accid
                    let token = info.token
                    location.href = convertRequestURL(`?token=${token}&uid=${myAccid}#/chat/p2p-${accid}`,'chat')
                })
                .catch(error => {
                    console.error(error)
                    this.hideLoading()
                })
            },
            goContactDetail(){
                let bizRole = this.curUser.user.bizRole
                let type
                if(bizRole == 'B'){
                    type = 'lend'
                }
                this.$router.push({
                    name:'contact-detail',
                    params:{
                        id:this.curUser.contactId
                    },
                    query:{
                        type:type
                    }
                })
            },
            scrollToLetter(index){
                let letterEl = $(this.$refs.content).find('.contact__letter')
                let scrollTop = $(this.$refs.content).scrollTop()

                if(!this.letterPos.length){
                    $(this.$refs.content).scrollTop(0)
                    letterEl.each( (index) => {
                        let top = letterEl.eq(index).offset().top - 55
                        this.letterPos.push(top)
                    })
                }

                if(this.os == 'Android'){
                    // $('body').css('visibility','hidden')
                    $(this.$refs.content).scrollTop(this.letterPos[index])
                    // $('body').css('visibility','visible')
                }
                if(this.os != 'Android'){
                    let o = {
                      scroll: scrollTop
                    }
                    dynamics.animate(o, {
                      scroll: this.letterPos[index],
                    }, {
                      change: ()=> {
                        $(this.$refs.content).scrollTop(o.scroll)
                      },
                      type: dynamics.easeInOut,
                      duration: 600,
                      friction: 50
                    })
                }

            },
            getList(num){
                this.showLoading()
                contactApi.list()
                .then(result=>{
                    this.list = result
                    this.pageLoaded = true
                    this.hideLoading()
                })
                .catch(error => {
                    console.error(error)
                    this.pageLoaded = true
                    this.hideLoading()
                })
            },
            redhot(num){
                contactApi.redhot()
                .then(result=>{
                    this.isRedhot = result.haveRedPoint
                })
                .catch(error => {
                    console.error(error)
                })
            }
        },
        created(){
            this.getList()
            this.redhot()
        }
    }
</script>

<style lang="scss">
    @import "../sass/variables";
    @import "../sass/extends";
    @import "../sass/mixins";
    .contact-index{
        .wrapper{
            padding-bottom: 100px;
            padding-top: 60px;
        }
        .contact__add{
            position: absolute;
            z-index:2;
            top:0;
            left:0;
            right:0;
            background-color: #fff;
            height: 56px;
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding:0 16px 0 24px;
            border-bottom: 1px solid $sectionColor;
        }
        .contact-head-box{
            background-color: $backgroundColor;
            overflow:hidden;
            position: relative;
            z-index:1;
        }
        .contact-head{
            display: flex;
            justify-content: space-between;
            align-items: center;
            background-color: #fff;
        }
        .contact__search{
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 0 8px;
            margin: 8px;
        }
        .contact__new{
            padding:15px 16px;
            .iconfont{
                display: block;
                font-size: 14px;
                width: 14px;
                height: 14px;
                padding-left: 5px;
            }
            .new{
                color:$importColor;
            }
            .contact-head__right{
                position: relative;
                &.redhot{
                    &:after{
                        content:'';
                        position: absolute;
                        right:-5px;
                        top:-5px;
                        background-color: $orange;
                        width: 8px;
                        height: 8px;
                        border-radius:50%;
                    }
                }
            }
        }
        .contact-head__left{
            display: flex;
            align-items: center;
            flex:1;
            input{
                padding: 8px 0;
                display: block;
                flex:1;
            }
            .icon{
                display: flex;
                align-items: center;
                width: 24px;
                height:24px;
                padding-right: 16px;
                img{
                    width: 100%;
                }
            }
        }
        .contact-head__right{
            @extend %font-caption;
            display: flex;
        }
        .contact__total{
            @extend %font-body1;
            color:$importColor;
        }
        .contact__mask{
            position: absolute;
            top:0;
            left:0;
            right:0;
            bottom:0;
            background-color: rgba(0,0,0,.38);
        }
        .contact__search-detail{
            position: absolute;
            top:55px;
            left:0;
            right:0;
            bottom:0;
            z-index:2;
            background-color: $backgroundColor;
        }
        .contact__button{
            color:$orange;
            text-align: right;
            position: relative;
            .icon-plus{
                font-size: 24px;
                width: 24px;
                height: 24px;
                line-height: 24px;
                position: absolute;
                right:35px;
                top:50%;
                margin-top:-12px;
                &:before{
                    position: absolute;
                    top:0;
                    left:0;
                    right:0;
                    bottom:0;
                }
            }
        }
        .contact__box{
            border-bottom: 1px solid $sectionColor;
            margin-bottom: 6px;
            padding-bottom: 8px;
            &:last-child{
                border-bottom: none;
            }
        }
        .contact__letter{
            @extend %font-body2;
            padding:0 24px;
            line-height: 48px;
        }
        .contact__item{
            display: flex;
            align-items: center;
            height: 56px;
            padding:0 16px;
            position: relative;
            img{
                width: 40px;
                height: 40px;
                border-radius:50%;
                border-bottom: 1px solid $sectionColor;
                box-sizing: border-box;
            }
            p{
                @extend %font-subhead;
                color:$importColor;
                padding-left: 16px;
            }
            span{
                display: block;
                @extend %font-caption;
                padding-left: 16px;
            }
            .new{
                padding:1px 6px;
                background-color: $orange;
                color:#fff;
                border-radius:10px;
                margin-left: 8px;
                @extend %font-caption;
            }
        }
        .operate{
            position: absolute;
            display: flex;
            justify-content: space-between;
            top:100%;
            left:9px;
            right:9px;
            background-color: #fff;
            border-radius:2px;
            padding:24px 16px 16px 16px;
            box-shadow:0 0 8px 0 rgba(0,0,0,0.12), 0 8px 8px 0 rgba(0,0,0,0.12);
            transition:all ease 150ms;
            &:before{
                content:'';
                position: absolute;
                top:-16px;
                left:20px;
            }
            &.top{
                &:before{
                    @include triangle(16px 16px,#fff,top);
                }
            }
            &.bottom{
                &:before{
                    @include triangle(16px 16px,#fff,bottom);
                    top:auto;
                    bottom:-16px;
                }
            }
        }
        .operate__item{
            &:first-child{
                padding-left: 8px;
            }
            padding-left: 24px;
            text-align: center;
            span{
                display: block;
            }
            .font-body2{
                padding-top: 7px;
            }
            img{
                width: 25px;
                height: 25px;
                border-radius:0;
            }
        }
        .operate__left{
            display: flex;
            flex:1;
            position: relative;
            &:before{
                content:'';
                position: absolute;
                right:0;
                top:5px;
                bottom:5px;
                border-right:1px solid $sectionColor;
            }
        }
        .operate__right{
            display: flex;
            .operate__item{
                padding-left: 22px;
            }
        }
        .contact__letters{
            @extend %font-caption;
            position: absolute;
            text-align: center;
            right:0;
            top:50%;
            transform:translate(0,-50%);
            max-height: 100%;
            overflow: auto;
            padding: 70px 0;
            box-sizing: border-box;
        }
        .contacrt__letters-item{
            padding-top: 4px;
            padding-bottom: 4px;
            padding-right:8px;
            padding-left: 20px;
            &:active{
                color:$orange;
            }
        }
        .operate-modal{
            position: absolute;
            overflow:auto;
            top:0;
            left:0;
            right:0;
            bottom:0;
            z-index:3;
            transition:all ease 150ms;
            &.fade-enter .operate,
            &.fade-leave-active .operate {
                opacity:1;
                transform: translate3d(0,-20px,0) scale(.95);
            }
        }
        .operate-modal-mask{
            width: 100%;
            height: 100.1%;
            background-color: $sectionColor;
        }
    }

</style>
